<template>
  
  <view v-if="visible" class="emergency-modal">
    <!-- 遮罩层 -->
    <view class="modal-mask" @click="handleClose"></view>

    <!-- 弹框内容 -->
    <view class="modal-content">
      <!-- 订单标题栏 -->
      <view class="job-info">
        <image src="/static/image/z99.png" class="job-icon"></image>
        <view class="job-details">
          <view class="job-title">
            <text class="title-text text-first">{{ title }}</text>
            <text class="salary">{{ salary }}</text>
          </view>
          <view class="job-requirements">
            <text class="text-item">{{ peopleCount }}人</text>
            <text class="text-item">{{ requirements }}</text>
            <text class="text-item">{{ time }}</text>
            <text class="text-item">{{ skills }}</text>
          </view>
          <!-- 修改地点和距离的布局 -->
          <view class="location-container">
            <view class="location">
              <text>地点：</text>
              <text>{{ location }}</text>
            </view>
            <view class="distance">
              <text>距离：</text>
              <text>{{ distance }}</text>
            </view>
            <view class="button">
              <button class="apply-btn" @click="handleApply">{{ applyText }}</button>
            </view>
          </view>


        </view>

        <!-- 关闭按钮 -->
        <view class="close-btn" @click="handleClose">
          <uni-icons type="close" size="32" color="#FFFFFF"></uni-icons>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { request } from '@/utils/request';

export default {
  name: 'EmergencyModal',
  data() {
    return {
      visible: false,
      title: '',
      salary: '',
      peopleCount: 0,
      requirements: '',
      time: '',
      skills: '',
      location: '',
      distance: '',
      applyText: '立即报名',
      taskId: null,
      enableEmergencyTask: true // 新增：控制是否处理紧急任务通知
    };
  },
  mounted() {
    console.log('EmergencyModal mounted');
    // 注册WebSocket消息监听
    this.listenWebSocketMessage();

    // 监听紧急任务通知控制事件
    uni.$on('enableEmergencyTask', this.enableEmergencyTaskHandler);
    uni.$on('disableEmergencyTask', this.disableEmergencyTaskHandler);
  },
  beforeUnmount() {
    // 移除WebSocket消息监听
    uni.$off('websocket-message', this.handleWebSocketMessage);
    // 移除事件监听器
    uni.$off('enableEmergencyTask', this.enableEmergencyTaskHandler);
    uni.$off('disableEmergencyTask', this.disableEmergencyTaskHandler);
  },
  methods: {
    listenWebSocketMessage() {
      // 使用组件实例方法作为回调，确保this指向正确
      uni.$off('websocket-message', this.handleWebSocketMessage);
      uni.$on('websocket-message', this.handleWebSocketMessage);
    },
    handleWebSocketMessage(message) {

      try {
        let parsedMessage;
        // 检查是否是有效的JSON格式
        if (typeof message === 'string' && message && (message.startsWith('{') || message.startsWith('['))) {
          parsedMessage = JSON.parse(message);
        } else {
          console.warn('接收到非JSON格式的消息:', message);
          return;
        }

        // 处理紧急任务通知 - 只有在启用状态下才处理
        if (parsedMessage.type === 'emergency_task' && this.enableEmergencyTask) {
          console.log('收到紧急任务通知:', parsedMessage);
          this.taskId = parsedMessage.data.task_id;
          this.getEmergencyTask();
        }
      } catch (error) {
        console.error('WebSocket消息处理失败:', error, '原始消息:', message);
      }
    },
    // 获取紧急任务详情
    getEmergencyTask() {
      if (!this.taskId) return;

      request({
        url: 'Taskapply/get_emergency_task',
        method: 'GET',
        data: {
          task_id: this.taskId,
          user_lat: uni.getStorageSync('lat'),
          user_lng: uni.getStorageSync('lng'),
        }
      }).then(res => {
        if (res.code === 200) {
          // 更新弹窗数据并显示
          const taskData = res.data;
          this.title = taskData.title;
          this.salary = taskData.salary;
          this.peopleCount = taskData.peopleCount;
          this.requirements = taskData.requirements;
          this.time = taskData.time;
          this.skills = taskData.skills;
          this.location = taskData.location;
          this.distance = taskData.distance;
          this.visible = true;
        } else {
          uni.showToast({ title: res.msg || '获取任务详情失败', icon: 'none' });
        }
      }).catch(err => {

        uni.showToast({ title: '网络错误，无法获取任务详情', icon: 'none' });
      });
    },
    handleClose() {
      this.visible = false;
    },
    handleApply() {
      if (!this.taskId) {
        uni.showToast({ title: '任务信息不存在', icon: 'none' });
        return;
      }

      request({
        url: 'Taskapply/apply_task',
        method: 'POST',
        data: {
          task_id: this.taskId
        }
      }).then(res => {
        if (res.code === 200) {
          uni.showToast({ title: '报名成功', icon: 'success' });
          this.visible = false;
        } else {
          uni.showToast({ title: res.msg || '报名失败', icon: 'none' });
        }
      }).catch(err => {
        console.error('报名请求失败:', err);
        uni.showToast({ title: '网络错误，报名失败', icon: 'none' });
      });
    },
    // 启用紧急任务通知
    enableEmergencyTaskHandler() {
      this.enableEmergencyTask = true;
      console.log('已启用紧急任务通知');
    },
    // 禁用紧急任务通知
    disableEmergencyTaskHandler() {
      this.enableEmergencyTask = false;
      console.log('已禁用紧急任务通知');
    }
  }
}
</script>

<style lang="scss" scoped>
.emergency-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10099;
  /* 提升层级，确保在tab栏和签到组件之上 */
}

.modal-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
  width: 85%;
  background-color: #fff;
  border-radius: 26rpx;
  box-shadow: 0rpx 3rpx 13rpx 0rpx rgba(14, 28, 55, 0.35);
  padding: 30rpx;
  position: relative;
  z-index: 1;
  padding-bottom: 6rpx;
}

.job-info {
  display: flex;
}

.job-icon {
  width: 30rpx;
  height: 32rpx;
  margin-right: 15rpx;
  position: relative;
  top: 7rpx;

}

.job-details {
  flex: 1;
}

.job-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 26rpx;
}

.job-title .text-first {
  font-family: Source Han Sans CN;
  font-weight: 500;
  font-size: 32rpx;
  color: #0E1C37;
}

.salary {
  font-family: Source Han Sans CN;
  font-weight: 500;
  font-size: 32rpx;
  color: #F71737;
}

.job-requirements {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 26rpx;
  width: 109%;
  justify-content: start;
  margin-left: 23rpx;
}

.job-requirements .text-item {

  background-color: #EEF2F3;
  padding: 8rpx 21rpx;
  border-radius: 10rpx;
  font-weight: 400;
  font-size: 22rpx;
  color: #888B9A;
  /* width: calc(50% - 5rpx) ; */
  margin-bottom: 10rpx;
  box-sizing: border-box;
}

.job-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 24rpx;
  color: #999;
}

.location-container {
  position: relative;
  /* 使用弹性布局实现垂直排列 */
  display: flex;
  flex-direction: column;
  gap: 17rpx;
  margin-bottom: 26rpx;
  margin-left: 24rpx;
}

.button {
  position: absolute;
  right: 6rpx;
  top: 15rpx;

}

.location,
.distance {
  font-size: 22rpx;
  color: #888B9A;
}

.distance {
  font-size: 22rpx;
  color: #888B9A;
}

// .location-icon {
// 	width: 24rpx;
// 	height: 24rpx;
// 	margin-right: 5rpx;
// }


.apply-btn {
  background-color: #BEFF32;
  /* 调整为效果图中的绿色 */


  color: #0E1C37;
  border: none;


  width: 172rpx;
  height: 56rpx;
  background: #BEFF32;
  border-radius: 12rpx;
  ;
  font-size: 26rpx;
  font-weight: 400;

}

.close-btn {
  position: absolute;
  bottom: -80rpx;
  right: 320rpx;
}
</style>